<template>
  <div class="device-box">
    <CardBox title="设备列表"></CardBox>
    <div class="content-container">
      <div class="device-grid">
        <div
          class="device-item"
          v-for="(item, index) in devices"
          :key="index"
          @click="handleDeviceClick(item)"
          :class="{ active: currentContent.name === item.name }"
        >
          <div class="device-active"></div>
          <div class="device-info">
            <div class="device-type">
              <img :src="require(`@/assets/img/device-status-${index + 1}.png`)" alt="" class="device-icon"/>
              <img :src="require(`@/assets/img/device-status-active-${index + 1}.png`)" alt="" v-if="currentContent === item.name" class="device-icon"/>
              <span class="device-name">{{ item.name }}</span>
              <span class="device-number">{{item.status.normal + item.status.offline + item.status.error}}</span>
            </div>
          </div>
          <div class="device-chart" :ref="'deviceChart' + index"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import CardBox from "@/components/Global/CardBox.vue";
import { getDeviceData } from "@/api/modules/home/device";
import { EventBus } from "../../utils/event-bus";
export default {
  components: {
    CardBox,
  },
  props: {
    currentContent: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      devices: [],
      deviceCharts: [],
    };
  },
  mounted() {
    this.$api.device.getDeviceList().then((res) => {
      setTimeout(() => {
        this.devices = res;
        this.initDeviceCharts();
        // 发出设备列表加载完成事件
        this.$emit("devices-loaded", this.devices);
        // 设置默认选中的设备
        if (this.devices.length > 0) {
          this.handleDeviceClick(this.devices[1]);
        }
      }, 500);
    });
  },
  beforeDestroy() {
    this.deviceCharts.forEach((chart) => {
      chart && chart.dispose();
    });
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    handleDeviceClick(device) {
      // 先获取设备数据
      this.getDeviceData(device);
      // 然后发送点击事件
      this.$emit("device-click", device);
      // 在地图上添加标注
      this.addMapMarkers(device);
      console.log(device);
      this.currentContent = device;
    },
    initDeviceCharts() {
      // 清理旧的图表实例
      this.deviceCharts.forEach((chart) => {
        chart && chart.dispose();
      });
      this.deviceCharts = [];

      this.$nextTick(() => {
        this.devices.forEach((device, index) => {
          const chartDom = this.$refs["deviceChart" + index];
          if (chartDom && chartDom[0]) {
            const chart = echarts.init(chartDom[0]);

            const total =
              device.status.normal +
              device.status.offline +
              device.status.error;
            const option = {
              backgroundColor: "transparent",
              tooltip: {
                trigger: "item",
                formatter: function (params) {
                  const status = params.data.name;
                  const count = params.data.value;
                  return `${status}: ${count}台`;
                },
              },
              series: [
                {
                  type: "pie",
                  radius: ["60%", "70%"],
                  avoidLabelOverlap: false,
                  silent: false,
                  itemStyle: {
                    borderColor: "#00DCFF",
                    borderWidth: 2,
                  },
                  label: {
                    show: false,
                  },
                  labelLine: {
                    show: false,
                  },
                  data: [
                    {
                      name: "正常",
                      value: device.status.normal,
                      itemStyle: { color: "#00DCFF" },
                    },
                    {
                      name: "故障",
                      value: device.status.error,
                      itemStyle: { color: "#D8D8D8" },
                    },
                    {
                      name: "离线",
                      value: device.status.offline,
                      itemStyle: { color: "#D8D8D8" },
                    },
                  ],
                },
              ],
            };

            chart.setOption(option);
            this.deviceCharts.push(chart);
          }
        });
      });
    },
    getDeviceData(device) {
      switch (device.name) {
        case "红外":
          this.$api.device.getHezeCollectList().then((res) => {
            device.dialogData.videos = res;
          });
          break;
        case "视频":
          this.$api.device.getIcVideoCollectList().then((res) => {
            device.dialogData.videos = res;
          });
          break;
        case "声纹":
          this.$api.device.getSjkjCollectList().then((res) => {
            device.dialogData.audios = res;
          });
          break;
        case "昆虫":
          this.$api.device.getWdtecCollectList().then((res) => {
            device.dialogData.images = res;
          });
          break;
        case "气象":
          this.$api.environment.getDeviceList("qixiang").then(res => {
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
            const day = currentDate.getDate();
            const hours = String(currentDate.getHours()).padStart(2, '0');
            const minutes = String(currentDate.getMinutes()).padStart(2, '0');
            const seconds = String(currentDate.getSeconds()).padStart(2, '0');
            const today=`${year}-${month}-${day} ${
                    hours}:${
                    minutes}:${
                    seconds}`;
            const lastDay=`${year}-${month}-${day-1} ${
                    hours}:${
                    minutes}:${
                    seconds}`;
            var deviceId=0;
            for (let i = 0; i < res.length; i++) {
              if(res[i].localStatus==1){
                deviceId=res[i].id;
                break;
              }
            }
            var params={
              start_date:"2025-04-11",
              end_date:"2025-05-07",
              varNameList:null,
              deviceId:deviceId
            };
            params.start_date=lastDay;
            params.end_date=today;
            params.deviceId = deviceId;
            this.$api.environment.getVarList("qixiang",params).then(res => {
              device.dialogData = res;
            });
          });

          break;
        case "土壤":
          this.$api.environment.getDeviceList("turang").then(res => {
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
            const day = currentDate.getDate();
            const hours = String(currentDate.getHours()).padStart(2, '0');
            const minutes = String(currentDate.getMinutes()).padStart(2, '0');
            const seconds = String(currentDate.getSeconds()).padStart(2, '0');
            const today=`${year}-${month}-${day} ${
                    hours}:${
                    minutes}:${
                    seconds}`;
            const lastDay=`${year}-${month}-${day-1} ${
                    hours}:${
                    minutes}:${
                    seconds}`;
            var deviceId=0;
            for (let i = 0; i < res.length; i++) {
              if(res[i].localStatus==1){
                deviceId=res[i].id;
                break;
              }
            }
            var params={
              start_date:"2025-04-11",
              end_date:"2025-05-07",
              varNameList:null,
              deviceId:deviceId
            };
            params.start_date=lastDay;
            params.end_date=today;
            params.deviceId = deviceId;
            this.$api.environment.getVarList("turang",params).then(res => {
              device.dialogData = res;
            });
          });
          break;
        case "空气质量":
          this.$api.environment.getDeviceList("kongqi").then(res => {
            const currentDate = new Date();
            const year = currentDate.getFullYear();
            const month = currentDate.getMonth() + 1; // 月份从0开始，需要加1
            const day = currentDate.getDate();
            const hours = String(currentDate.getHours()).padStart(2, '0');
            const minutes = String(currentDate.getMinutes()).padStart(2, '0');
            const seconds = String(currentDate.getSeconds()).padStart(2, '0');
            const today=`${year}-${month}-${day} ${
                    hours}:${
                    minutes}:${
                    seconds}`;
            const lastDay=`${year}-${month}-${day-1} ${
                    hours}:${
                    minutes}:${
                    seconds}`;
            var deviceId=0;
            for (let i = 0; i < res.length; i++) {
              if(res[i].localStatus==1){
                deviceId=res[i].id;
                break;
              }
            }
            var params={
              start_date:"2025-04-11",
              end_date:"2025-05-07",
              varNameList:null,
              deviceId:deviceId
            };
            params.start_date=lastDay;
            params.end_date=today;
            params.deviceId = deviceId;
            this.$api.environment.getVarList("kongqi",params).then(res => {
              device.dialogData = res;
            });
          });
          break;
      }
    },
    getMarkerIcon(deviceType, status) {
      const statusMap = {
        1: "normal",
        2: "offline",
        3: "abnormal",
      };
      const statusSuffix = statusMap[status] || "normal";
      return require(`@/assets/img/${deviceType}-${statusSuffix}.png`);
    },
    addMapMarkers(device) {
      // 根据设备类型获取对应的标注数据
      let apiUrl = "";
      let deviceType = "";

      switch (device.name) {
        case "红外":
          apiUrl = "/cockpitapi/home/getHezeDeviceList";
          deviceType = "hongwai";
          break;
        case "视频":
          apiUrl = "/cockpitapi/home/getIcvideoDeviceList";
          deviceType = "shipin";
          break;
        case "声纹":
          apiUrl = "/cockpitapi/home/getSjkjDeviceList";
          deviceType = "shengwen";
          break;
        case "昆虫":
          apiUrl = "/cockpitapi/home/getWdtecDeviceList";
          deviceType = "chongqing";
          break;
        case "气象":
          apiUrl = "/cockpitapi/habitat/qixiang/getDeviceList";
          deviceType = "qixiang";
          break;
        case "土壤":
          apiUrl = "/cockpitapi/habitat/turang/getDeviceList";
          deviceType = "turang";
          break;
        case "空气质量":
          apiUrl = "/cockpitapi/habitat/kongqi/getDeviceList";
          deviceType = "kongqi";
          break;
        default:
          return;
      }

      // 调用API获取设备位置数据
      this.$api.device
        .getDeviceLocation(apiUrl)
        .then((response) => {
          if (response) {
            // 通过 Vuex 更新标注数据
            this.$store.dispatch("map/updateMarkers", {
              markers: response.map((item) => ({
                ...item,
                icon: this.getMarkerIcon(deviceType, item.localStatus),
              })),
              deviceType: device.name,
            });
          }
        })
        .catch((error) => {
          console.error("Error fetching device locations:", error);
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.device-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  height: 300px;
  overflow: hidden;
}

.device-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  .device-active {
    width: 4px;
    height: 16px;
    background: #07ffe5;
    border-radius: 2px;
    margin-right: 32px;
    opacity: 0;
  }
}

.device-item.active {
  .device-active {
    opacity: 1;
  }
  .device-info {
    .device-name {
      color: #07ffe5;
    }
  }
}

.device-chart {
  width:80px;
  height:40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.device-info {
  text-align: center;
  user-select: none;
  font-size: 18px;
  color: #fff;
  .device-type {
    color: #fff;
    font-size: 15px;
    position: relative;
    .device-name {
      width: 100px;
      display: inline-block;
      text-align: center;
    }
    .device-icon{
      position: absolute;
      left: -10px;
      top: 0px;
    }
  }
}
</style>